﻿/********************************************************************
    created:	2015/07/06  16:54
    file base:	CSVReader
    file ext:	cs
    author:		github tikonen

    purpose:	CSV的读取，只需要将csv文件放置在Resource下某目录即可，比如放在resource/data下，那么：
                CSVReader testReader = new CSVReader();
                testReader.Load("data/example");
                testReader.PrintData();
                string testValue = testReader.getById("1", "name");
                int testIntValue = testReader.getIntById("2", "age");
                float testFloatValue = testReader.getFloatById("3", "speed");
*********************************************************************/

using CodeStage.AntiCheat.ObscuredTypes;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using UnityEngine;
using Util;

public partial class CSVReader {
    private static string LINE_SPLIT_RE = @"\r\n|\n\r|\n|\r";

    private string m_fileName = "";
    private const char _Disconnect = '#';//连接符
    private static List<List<string>> _special = new List<List<string>>(){//特殊替换符号
       new List<string>(){"~", "\n" },
    };
    public string FileName {
        get { return m_fileName; }
        set { m_fileName = value; }
    }

    public string[] m_keys;
    private List<Dictionary<string, string>> m_dataList = new List<Dictionary<string, string>>();
    private Dictionary<string, Dictionary<string, string>> m_datadic = new Dictionary<string, Dictionary<string, string>>();

    public Dictionary<string, Dictionary<string, string>> Datadic {
        get { return m_datadic; }
    }

    public List<Dictionary<string, string>> DataList {
        get { return m_dataList; }
    }


    public CSVReader(string fileName) {
        Load(fileName);
    }

    public CSVReader(string fileName, string content) {
        LoadContent(fileName, content);
    }

   

    /// <summary>
    /// 载入指定的csv文件，并进行初始化
    /// </summary>
    /// <param name="fileName"></param>
    public void Load(string fileName) {
        m_fileName = fileName;
        ReadContent(DataTablesManager.Load(m_fileName));
        RefreshDataDic();
    }

    private void LoadContent(string filename, string content) {
        m_fileName = filename;
        ReadContent(content);
        RefreshDataDic();
    }

    private void ReadContent(string txt) {
        var lines = Regex.Split(txt, LINE_SPLIT_RE);
        if (lines.Length <= 1) return;

        var header = lines[1].Split(_Disconnect);
        m_keys = header;
        for (var i = 4; i < lines.Length; i++) {
            var values = lines[i].Split(_Disconnect);
            if (values.Length == 0 || values[0] == "") continue;

            var entry = new Dictionary<string, string>();
            for (var j = 0; j < header.Length && j < values.Length; j++) {
                string value = values[j];
                //单节点替换操作
                for (int k = 0; k < _special.Count; k++) {
                    value = value.Replace(_special[k][0], _special[k][1]);
                }
                entry[header[j]] = value;
            }
            m_dataList.Add(entry);
        }
    }
    public void RefreshDataDic() {
        m_datadic.Clear();
        for (int i = 0; i < m_dataList.Count; i++) {
            Dictionary<string, string> data = m_dataList[i];
            string typeName = m_keys[0];
            string id = "-1";
            data.TryGetValue(typeName, out id);
            if (id == "-1") {
#if UNITY_EDITOR
                debug.log(m_fileName, typeName, id, "  error");
                continue;
#endif
            }

            Dictionary<string, string> d;
            if (m_datadic.TryGetValue(id, out d)) {
                debug.log(true, debug.Level.error_3, m_fileName, typeName, id, "  have added");
            }
            else {
                m_datadic.Add(id, data);
            }
        }
    }
    /// <summary>
    /// 打印数据，用于调试
    /// </summary>
    public void PrintData() {
#if UNITY_EDITOR
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < m_dataList.Count; ++i) {
            foreach (KeyValuePair<string, string> keyValue in m_dataList[i]) {
                string valueString = keyValue.Value.ToString();
                stringBuilder.Append(valueString);
                stringBuilder.Append(_Disconnect);
            }
            stringBuilder.Append("\n");
        }

        debug.log(true, debug.Level.warning_2, "CSV file: ", m_fileName, ", data is: \n", stringBuilder.ToString());
#endif
    }

    /// <summary>
    /// 返回行数
    /// </summary>
    /// <returns></returns>
    public int num() {
        return m_dataList.Count;
    }

    /// <summary>
    /// 返回key的个数
    /// </summary>
    /// <returns></returns>
    public int keynum() {
        return m_keys.Length;
    }
}
